<?php
namespace Home\Controller;
use Think\Controller;
/**
* 登录控制器
*/
class LoginController extends Controller{
	public function index(){
		if (IS_POST) {
            $name = I('username');
            // $pwd  = I('post.password');
            // $data = M('user')->where(array('username'=>$name,'password'=>md5($pwd)))->find();
            $data = M('user')->where(array('id'=>$name))->find();
            
            if ($data) {
                session('uid',$data);
               
                $this->redirect('Index/index');
            }else{
                session('uid',null);

                $result['status']=0;
                $result['message']='账号密码不匹配';
                $this->error('账号密码不匹配');
            }
        }else{

            $this->display();
        }
	}

    public function login(){
        if (IS_POST) {
            $mobile = I('post.mobile');
            $pwd  = I('post.password');
            $data = M('user')->where(array('phone'=>$mobile,'password'=>md5($pwd)))->find();

            if ($data) 
            {   
                session('userids',$data['id']);
                session('uid',$data);
                A('Index')->sendoutlogin($data['id']);
                $result["result"] = true;
                $result['message'] = "登录成功";
                $this->ajaxReturn($result);
            }else
            {
                $result["result"] = false;
                $result["message"] = '登录失败';
                $this->ajaxReturn($result);
            }
        }
    }
    // 短信验证码
    public function code(){
        if (IS_POST) {
            $mobile=I('post.mobile');
            if(!$mobile){
                $this->error('请输入手机号码！');
            }
            if(!preg_match("/1[34578]{1}\d{9}$/",$mobile)){
                $this->error('请输入正确手机号码！');  
            }
            $phone = M('user')->where(array('phone'=>$mobile))->find();
            if ($phone) {
                $this->error('手机号已被注册');
            }
            if (S('cards'.$mobile)) {
                $this->error('请勿重复调用接口');
            }
            $data = M('duanxin')->order('id desc')->select();
            $options['accountsid']=$data[0]['accountsid'];//"f9d4bf710e1ce67b67eac6780d661b81";
            $options['token']=$data[0]['token'];//"670d53d232621c7a640cf79eb346fe09";
            $ucpass = new \Org\Com\Ucpaas($options);
            //短信验证码（模板短信）,默认以65个汉字（同65个英文）为一条
            $appId = $data[0]['appid'];//"82c35f120b554161a3164cf43307202e";
            $to = $mobile;
            $templateId = $data[0]['templateid'];//"23317";
            $randStr = str_shuffle('123456789');
            $rand = substr($randStr,0,6);
            S('card'.$mobile,$rand,120);
            S('cards'.$mobile,$rand,58);
            $param=$rand.',2';
            $arr=$ucpass->templateSMS($appId,$to,$templateId,$param);
            // dump($arr);exit();
            // $this->error($arr);
            if ($arr['respCode']==000000) {
                $this->success('发送成功');
            }else{
                $this->error('发送失败');
            }
        }
    }

    // 绑定手机
    public function mobile(){
        if (IS_POST) {
            $user = I('post.');

            if ($user['mobile']=='') 
            {
                $this->error('手机号为空，请输入');
            }
            if ($user['sms_code']=='') 
            {
                $this->error('验证码为空，请输入');
            }

            $code=S('card'.$user['mobile']);
            if ($user['sms_code']!=$code) 
            {
                $this->error('验证码不对，请重新输入');
            }

            $phone = M('user')->where(array('phone'=>$user['mobile']))->find();
            if ($phone) {
                $this->error('手机号已被注册');
            }
            $data=M('user')->where(array('id'=>session('uid.id')))->save(array('phone'=>$user['mobile']));

            if ($data === fales) 
            {
                $this->error('网络超时，请重试！');
            }else
            {
                $this->success('提交成功');
            }
        }
    }

    // 注册
    public function register(){
        if (IS_POST) {
            $user = I('post.');

            if ($user['mobile']=='') 
            {
                $this->error('手机号为空，请输入');
            }
            if ($user['sms_code']=='')
            {
                $this->error('验证码为空，请输入');
            }
            if ($user['sex']=='') 
            {
                $this->error('性别不能为空，选择后不可修改！');
            }
            $phone = M('user')->where(array('phone'=>$user['mobile']))->find();
            if ($phone) {
                $this->error('手机号已被注册');
            }
            $code=S('card'.$user['mobile']);

            if ($user['sms_code']!=$code) 
            {
                $this->error('验证码不对，请重新输入');
            }

            $tui_id = session('tui_id') ? session('tui_id') : '0';

            $list = array(
                'phone'   => $user['mobile'],
                'add_time' => time(),
                'tui_id'   => $tui_id,
                'sex'      => $user['sex'],
                'star'     => $user['star'],
                'age'      => $user['age'],  
                'password' => md5($user['password']),
                );
            // $this->error($user['isweb']);
            //判断是不是web注册
            if ($user['isweb'] == '101') 
            {   
                session(null);
                // 手机号第一次注册
                $content = '欢迎注册。next';
                $data=M('user')->add($list);
                session('userid',$data);// 第一次手机注册标识
                $mess = array(
                    'fa_id'  => '0',
                    'shou_id'=>$data,
                    'add_time'=>time(),
                    'type'   => '0',
                    'content'=> $content,
                    'interval'=>intval(time()/300),
                    );
                $list['id']=$data;
                session('uid',$list);
                M('message')->add($mess);// 第一次注册系统消息
                M('message_list')->add(array('fa_id'=>'0','shou_id'=>$data,'news'=>$content,'add_time'=>time()));
                system_to_one($data,$content);
            }
            // 判断是不是 微信第一次登录注册
            $open_id = session('uid.openid');
            if ($open_id) 
            {   
                // 如果有openid 但是跳转到注册来，说明是没有绑定手机号的，要来绑定手机号，
                $weixin = M('user')->where(array('openid'=>session('uid.openid')))->find();
                if ($weixin['phone'] == $user['mobile']) {
                    $this->error('微信已绑定过其他账号！');
                }
                $data=M('user')->where(array('openid'=>session('uid.openid')))->save($list);
            }
            // $this->error($user['isweb']);
            if (!$data) 
            {
                $this->error('网络超时，请重试！');
            }else
            {
                $this->success('提交成功');
            }
        }
    }

    // 忘记密码
    public function wpwd(){
        if (IS_POST) {
            $user = I('post.');

            if ($user['mobile']=='') 
            {
                $this->error('手机号为空，请输入');
            }
            if ($user['sms_code']=='') 
            {
                $this->error('验证码为空，请输入');
            }

            if ($user['password']=='') 
            {
                $this->error('密码为空，请输入');
            }

            $code=S('card'.$user['mobile']);
            if ($user['sms_code']!=$code) 
            {
                $this->error('验证码不对，请重新输入');
            }

            $data=M('user')->where(array('id'=>session('uid.id')))->save(array('password'=>md5($user['password'])));

            if ($data === fales) 
            {
                $this->error('网络超时，请重试！');
            }else
            {
                $this->success('提交成功');
            }
        }
    }

    // 微信解绑
    public function backweixin(){
        $user_id = get_user();
        $data = M('user')->where(array('id'=>$user_id))->save(array('openid'=>''));

        if ($data) 
        {   
            session(null);
            $result["result"] = true;
            $result['message'] = "解绑成功";
            $this->ajaxReturn($result);
        }else
        {
            $result["result"] = false;
            $result["message"] = '解绑失败';
            $this->ajaxReturn($result);
        }
    }

    // 消息通知开关查询
    public function trueNews(){
        $user_id = get_user();
        $data = M('user')->where("id=$user_id")->getField('news');
        $result["result"] = true;
        $result['message'] = "查询成功";
        $result['id'] = $data;
        $this->ajaxReturn($result);
    }
    // 消息通知开关
    public function falesNews(){
        $user_id = get_user();
        $ids = M('user')->where("id=$user_id")->getField('news');
        $news = $ids == 0 ? 1 :0;  
        $data = M('user')->where("id=$user_id")->save(array('news'=>$news));
        $result["result"] = true;
        $result['message'] = "修改成功";
        $this->ajaxReturn($result);
    }
}